<template>
  <div class="mod-role">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="roleName"
            :label="$t('sys.roleName')+':'"
          >
            <el-input
              v-model="searchForm.roleName"
              type="text"
              clearable
              :placeholder="$t('sys.roleName')"
            />
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="resetForm()"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 搜索栏end -->
    <div class="main-container">
      <div class="operation-bar">
        <el-checkbox
          v-model="selectAll"
          class="all-check-btn"
          :disabled="!dataList.length"
          @change="onSelectAll"
        >
          {{ $t('publics.selectAll') }}
        </el-checkbox>
        <span
          v-if="dataListSelections.length"
          class="had-selected"
        >{{ $t('publics.selected') }} {{ dataListSelections.length }}</span>
        <div
          v-if="isAuth('sys:shopRole:save')"
          class="default-btn primary-btn"
          @click="onAddOrUpdate(0)"
        >
          {{ $t('crud.addBtn') }}
        </div>
        <div
          v-if="isAuth('sys:shopRole:delete')"
          :class="[!dataListSelections.length ? 'disabled-btn':'','default-btn']"
          @click="onDelete()"
        >
          {{ $t('sys.batchDelete') }}
        </div>
      </div>
      <div class="table-con">
        <el-table
          ref="tableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
          @selection-change="selectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            align="left"
            prop="roleName"
            :label="$t('sys.roleName')"
          >
            <template #default="scope">
              <span>{{ scope.row.roleName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            prop="remark"
            :label="$t('publics.remark')"
          >
            <template #default="scope">
              <span>{{ scope.row.remark || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            prop="createTime"
            :label="$t('sys.creationTime')"
          />
          <el-table-column
            align="center"
            :label="$t('crud.menu')"
            width="250"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('sys:shopRole:update')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.roleId)"
                >
                  {{ $t('temp.modify') }}
                </div>
                <div
                  v-if="isAuth('sys:shopRole:delete')"
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.roleId)"
                >
                  {{ $t('text.delBtn') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './add-or-update.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils'

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({
  username: '',
  nickName: ''
})
onMounted(() => {
  getDataList(page)
})

let tempSearchForm = null // 保存上次点击查询的请求条件
const dataList = ref([])
// 获取数据列表
const getDataList = (pageParam, newData = false) => {
  if (page) {
    const size = Math.ceil(page.total / page.pageSize)
    page.currentPage = (page.currentPage > size ? size : page.currentPage) || 1
  }
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  http({
    url: http.adornUrl('/sys/shopRole/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
  })
}

// 条件查询
const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}

const tableRef = ref(null)
const selectAll = ref(false)
/**
 * 全选按钮
 */
const onSelectAll = () => {
  selectAll.value = tableRef.value?.getSelectionRows().length < dataList.value.length
  tableRef.value?.toggleAllSelection()
}
// 刷新回调用
const refreshChange = () => {
  getDataList(page)
}

const dataListSelections = ref([])
// 多选变化
const selectionChange = (val) => {
  dataListSelections.value = val
  selectAll.value = val.length === dataList.value.length
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList(page)
}

const onPageChange = (val) => {
  page.currentPage = val
  getDataList(page)
}

const resetForm = () => {
  searchForm.username = ''
  searchForm.nickName = ''
}

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
// 新增 / 修改
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}

// 删除
const onDelete = (id) => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.roleId
  })
  if (!ids.length) {
    return
  }
  ElMessageBox.confirm(`${$t('sys.makeSure')}${id ? $t('text.delBtn') : $t('sys.batchDelete')}${$t('text.menu')}`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/sys/shopRole'),
      method: 'delete',
      data: http.adornData(ids, false)
    }).then(() => {
      page.total = page.total - ids.length
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  }).catch(() => { })
}

</script>
<style lang="scss" scoped>
.mod-role {
}
</style>
